package server

import (
	"bufio"
	"io"
	"os"
	"strings"
)

type Map struct {
	pvpMap [][]int
	height int32
	wide int32
}

var PvpMap *Map

func GetMap() *Map {
	if PvpMap == nil {
		PvpMap = &Map{
			pvpMap: make([][]int,100),
		}
		for i:=0;i < 100;i++{
			PvpMap.pvpMap[i] = make([]int,135)
		}
		PvpMap.height = 100
		PvpMap.wide = 135
	}
	return PvpMap
}
var rows int
var cols int
func (m *Map) ReadMap() {
	strs := []string{}
	f, err := os.Open("conf/map.txt")
	if err != nil {
		panic(err)
	}
	defer f.Close()
	var lineCount = 1
	rd := bufio.NewReader(f)
	for {
		line, err := rd.ReadString('\n') //以'\n'为结束符读入一行
		if err != nil || io.EOF == err {
			break
		}
		if lineCount >= 5 {
			s := string([]byte(line)[1:(len(line) - 4)]) + "\n"
			strs = append(strs, strings.Replace(s,","," ",-1))
		}
		lineCount++
	}

	k := 0
	rows = len(strs)
	for i := 0 ;i < len(strs) ;i++{
		tmp := strs[i]
		for j := 0 ;j < len(tmp) ;j++{
			if tmp[j] != ' ' {
				m.pvpMap[i][k] = int(tmp[j])
				k++
			}
		}
		cols = k
		k = 0
	}
}

func (m *Map) IsCanWork(grid [][]int32) bool {
	for i := 0; i < len(grid); i++{
		if grid[i][0] >= m.height || grid[i][1] >= m.wide {
			return false
		}

		if m.pvpMap[int32(rows / 2) - grid[i][0]][int32(cols / 2) - grid[i][1]] == 0 {
			return false
		}
	}
	return true
}